package com.shiyi.shiyiaicodefather.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.shiyi.shiyiaicodefather.exception.ErrorCode;
import com.shiyi.shiyiaicodefather.exception.ThrowUtils;
import com.shiyi.shiyiaicodefather.manage.CosManager;
import com.shiyi.shiyiaicodefather.service.ScreenshotService;
import com.shiyi.shiyiaicodefather.utils.WebScreenshotUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 自动截图实现类
 */
@Service
@Slf4j
public class ScreenshotServiceImpl implements ScreenshotService {

  @Resource
  private CosManager cosManager;

  /**
   * 截图并保存图片到cos对象存储
   * @param webUrl 需要截图的网页url
   * @return 返回cos对象存储的url
   */
  @Override
  public String generateAndUploadScreenshot(String webUrl) {
    ThrowUtils.throwIf(StrUtil.isBlank(webUrl), ErrorCode.SYSTEM_ERROR ,"webUrl不能为空");
    log.info("开始生成网页截图，webUrl:{}", webUrl);
    String localScreenshotPath  = WebScreenshotUtils.saveWebPageScreenshot(webUrl);
    ThrowUtils.throwIf(StrUtil.isBlank(localScreenshotPath), ErrorCode.SYSTEM_ERROR ,"生成网页截图失败");

    try {
      String cosUrl = uploadScreenshotToCos(localScreenshotPath);
      ThrowUtils.throwIf(StrUtil.isBlank(cosUrl), ErrorCode.SYSTEM_ERROR ,"上传截图到对象存储失败");
      log.info("截图上传成功，cosUrl:{}", cosUrl);
      return cosUrl;
    } finally {
      //  清理本地文件
      cleanupLocalFile(localScreenshotPath);
    }
  }

  /**
   * 上传截图到对象存储
   *
   * @param localScreenshotPath 本地截图路径
   * @return 对象存储访问URL，失败返回null
   */
  private String uploadScreenshotToCos(String localScreenshotPath) {
    if (StrUtil.isBlank(localScreenshotPath)) {
      return null;
    }
    File file = new File(localScreenshotPath);
    if (!file.exists()) {
      log.error("截图文件不存在，localScreenshotPath:{}", localScreenshotPath);
      return null;
    }
    String fileName = UUID.randomUUID().toString().substring(0,8) + "_compress.jpg";
    String cosKey = generateScreenshotKey(fileName);
    return cosManager.uploadFile(cosKey,file);
  }

  /**
   * 生成截图的对象存储键
   * 格式：/screenshots/2025/07/31/filename.jpg
   */
  private String generateScreenshotKey(String fileName) {
    String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    return "/screenshots/" + datePath + "/" + fileName;
  }

  /**
   * 清理本地文件
   *
   * @param localFilePath 本地文件路径
   */
  private void cleanupLocalFile(String localFilePath) {
    File file = new File(localFilePath);
    if (file.exists()) {
      File parentFile = file.getParentFile();
      FileUtil.del(parentFile);
      log.info("本地图片已经清理：{}",localFilePath);
    }
  }
}
